package com.test.netty.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

@Slf4j
public class PingPongHandler extends ChannelInboundHandlerAdapter {

    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(WSConfig.PING_PONG_THREAD_SIZE);

    private ScheduledFuture<?> pingTask;

    @Override
    public void channelRegistered(final ChannelHandlerContext ctx) throws Exception {
        log.debug("client =>>" + ctx.channel().remoteAddress() + " Registered start ping task.");
        pingTask = scheduler.scheduleAtFixedRate(new Runnable() {
            public void run() {
                log.debug("Send WebSocket ping package to client =>> " + ctx.channel().remoteAddress());
                PingWebSocketFrame ping = new PingWebSocketFrame();
                ctx.channel().writeAndFlush(ping);
            }
        }, 5, WSConfig.PING_PONG_PERIOD_SECOND, TimeUnit.SECONDS);
        super.channelRegistered(ctx);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        log.debug("client =>>" + ctx.channel().remoteAddress() + " Unregistered stop ping task.");
        pingTask.cancel(true);
        super.channelUnregistered(ctx);
    }
}
